<template>
  <div class="group-container">
    <n-grid :cols="24" :x-gap="12" style="height: calc(100vh - 150px)">
      <!-- 左侧组织机构树 -->
      <n-gi :span="6">
        <OrgTree
          ref="orgTreeRef"
          @set="handleOrgSelect"
          @reload="handleOrgReload"
          @loaded="handleOrgTreeLoaded"
        />
      </n-gi>

      <!-- 右侧班组表格 -->
      <n-gi :span="18">
        <BusTable
          ref="groupTableRef"
          :columns="columns"
          :row-key="(row) => row.groupId"
          :scroll-x="1200"
          :pagination-config="{ pageSize: 20 }"
          :search-schemas="searchSchemas"
          :form-schemas="formSchemas"
          :form-rules="rules"
          :api-methods="apiMethods"
          :auto-load="false"
          modal-title="班组管理"
          @success="handleSuccess"
          @error="handleError"
        >
          <template #action="{ row }">
            <n-button text type="info" @click="handleManageMembers(row)">成员管理</n-button>
          </template>
        </BusTable>
      </n-gi>
    </n-grid>

  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, nextTick } from 'vue';
  import { useMessage } from 'naive-ui';
  import OrgTree from '@/views/businessPages/comp/org/orgTree.vue';
  import BusTable from '@/views/businessPages/comp/busTable/index.vue';

  // 导入API方法
  import {
    getGroupList,
    addGroup,
    updateGroup,
    deleteGroup,
    batchDeleteGroups,
  } from '@/api/business/memberManager/group';

  const message = useMessage();
  const orgTreeRef = ref();
  const groupTableRef = ref();

  // 成员管理弹窗相关
  const showMemberModal = ref(false);
  const currentGroupId = ref('');
  const currentGroupName = ref('');

  // 当前选中的组织ID
  const selectedOrgId = ref<string>('');

  // 添加一个 ref 来标识组织树是否已加载
  const orgTreeLoaded = ref(false);

  // 表格列配置
  const columns = [
    {
      type: 'selection',
      disabled(row: any) {
        return row.name === 'disabled';
      },
    } as any,
    {
      title: '序号',
      key: 'id',
      width: 80,
      fixed: 'left',
      render: (row: any, index: number) => {
        // 通过tableRef获取分页信息计算序号
        const pagination = groupTableRef.value?.getPaginationRef?.();
        if (pagination) {
          const currentPage = pagination.page || 1;
          const pageSize = pagination.pageSize || 20;
          return (currentPage - 1) * pageSize + index + 1;
        }
        // 如果获取不到分页信息，使用默认计算方式
        return index + 1;
      },
    },
    {
      title: '班组名称',
      key: 'groupName',
      width: 150,
    },
    {
      title: '所属机构',
      key: 'orgName',
      width: 200,
    },
    {
      title: '机构全路径',
      key: 'orgArrayName',
      width: 250,
    },
    {
      title: '班组长',
      key: 'monitorName',
      width: 120,
    },
    {
      title: '备注',
      key: 'remark',
      width: 150,
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      fixed: 'right',
    },
  ];

  // 搜索表单配置
  const searchSchemas = [
    {
      field: 'groupName',
      component: 'NInput',
      label: '班组名称',
      componentProps: {
        placeholder: '请输入班组名称进行搜索',
      },
    },
  ];

  // 表单配置
  const formSchemas = [
    {
      field: 'groupName',
      component: 'NInput',
      label: '班组名称',
      placeholder: '请输入班组名称',
      componentProps: {
        clearable: true,
      },
    },
    {
      field: 'orgId',
      component: 'NInput',
      label: '所属机构',
      placeholder: '请选择所属机构',
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'monitor',
      component: 'NInput',
      label: '班组长',
      placeholder: '请选择班组长',
      componentProps: {
        clearable: true,
      },
    },
    {
      field: 'remark',
      component: 'NInput',
      label: '备注',
      placeholder: '请输入备注信息',
      componentProps: {
        type: 'textarea',
        rows: 3,
      },
    },
  ];

  // 表单验证规则
  const rules = {
    groupName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入班组名称',
    },
    orgId: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择所属机构',
    },
  };

  // API 方法配置
  const apiMethods = {
    getList: getGroupList,
    add: addGroup,
    update: updateGroup,
    delete: deleteGroup,
    batchDelete: batchDeleteGroups,
  };

  // 处理组织树加载完成事件
  function handleOrgTreeLoaded() {
    orgTreeLoaded.value = true;
    // 获取根节点并初始化表格
    initializeTableWithRootNode();
  }

  // 处理组织机构选择
  function handleOrgSelect(id: string, name: string) {
    selectedOrgId.value = id;
    // 更新表格搜索条件中的组织ID
    if (groupTableRef.value) {
      // 触发表格重新加载，传入orgId参数
      groupTableRef.value.reload({ orgId: id });
    }
  }

  // 处理组织树重新加载
  function handleOrgReload() {
    console.log('组织树重新加载完成');
  }

  // 处理新增班组
  function handleAdd() {
    if (!selectedOrgId.value) {
      message.warning('请先选择一个组织机构');
      return;
    }

    // 设置表单中的默认组织ID
    if (groupTableRef.value) {
      groupTableRef.value.setFormModel({ orgId: selectedOrgId.value });
    }
  }

  // 处理成员管理
  function handleManageMembers(row: any) {
    currentGroupId.value = row.groupId;
    currentGroupName.value = row.groupName;
    showMemberModal.value = true;
  }

  // 处理操作成功
  function handleSuccess(operation: string) {
    const operationMap = {
      add: '新增',
      update: '编辑',
      delete: '删除',
      'batch-delete': '批量删除',
    };

    message.success(`${operationMap[operation] || operation}操作成功`);
    // 操作成功后重新加载数据，保持当前orgId过滤条件
    if (groupTableRef.value) {
      groupTableRef.value.reload({ orgId: selectedOrgId.value });
    }
  }

  // 处理成员操作成功
  function handleMemberOperationSuccess() {
    message.success('成员操作成功');
  }

  // 处理操作失败
  function handleError(error: any) {
    message.error('操作失败: ' + (error.message || '未知错误'));
  }

  // 初始化表格数据
  async function initializeTableWithRootNode() {
    if (orgTreeRef.value && typeof orgTreeRef.value.getRootNodeId === 'function') {
      const rootId = orgTreeRef.value.getRootNodeId();
      
      if (rootId) {
        selectedOrgId.value = rootId;
        if (groupTableRef.value) {
          groupTableRef.value.setDefaultParams({ orgId: rootId });
          groupTableRef.value.enableDataLoad();
          groupTableRef.value.reload({ orgId: rootId });
        }
      }
    }
  }

  // 组件挂载后初始化
  onMounted(async () => {
    // 等待组织树加载完成
    await nextTick();
    // 如果组织树已经加载完成，则直接初始化表格
    if (orgTreeLoaded.value) {
      initializeTableWithRootNode();
    }
  });
</script>

<style scoped>
  .group-container {
    padding: 16px;
    height: 100%;
    box-sizing: border-box;
  }

  :deep(.n-card) {
    height: 100%;
  }

  :deep(.n-data-table) {
    height: calc(100% - 100px);
  }
</style>
